package org.lanplay.server.entitymodel;

import java.io.Serializable;

import org.apache.wicket.model.IModel;

/**
 * Smart Entity Model.
 * 
 * Source: http://wicketinaction.com/2008/09/building-a-smart-entitymodel/
 * 
 * @param <T>
 *            Entity class
 */
public abstract class AbstractEntityModel<T extends Identifiable<?>> implements
		IModel<T> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private final Class<?> clazz;
	private Serializable id;

	protected T entity;

	public AbstractEntityModel(T entity) {
		clazz = entity.getClass();
		id = entity.getId();
		this.entity = entity;
	}

	public AbstractEntityModel(Class<? extends T> clazz, Serializable id) {
		this.clazz = clazz;
		this.id = id;
	}

	@Override
	public T getObject() {
		if (entity == null) {
			if (id != null) {
				entity = load(clazz, id);
				if (entity == null) {
					throw new EntityNotFoundException(clazz, id);
				}
			}
		}
		return entity;
	}

	@Override
	public void detach() {
		if (entity != null) {
			if (entity.getId() != null) {
				id = entity.getId();
				entity = null;
			}
		}
	}

	protected abstract T load(Class<?> clazz, Serializable id);

	@Override
	public void setObject(T object) {
		throw new UnsupportedOperationException(getClass()
				+ " does not support #setObject(T entity)");
	}
}